/*
 * Coding by Zhonghua. from 18-9-18 下午3:44.
 */

package cn.iotnova.opus.utils;

import androidx.annotation.NonNull;

import java.nio.ByteBuffer;
import java.nio.ByteOrder;

/*
object Uilts {
    fun byteArrayToShortArray(byteArray: ByteArray): ShortArray {
        val shortArray = ShortArray(byteArray.size / 2)
        ByteBuffer.wrap(byteArray).order(ByteOrder.nativeOrder()).asShortBuffer().get(shortArray)
        return shortArray
    }

    fun shortArrayToByteArray(shortArray: ShortArray): ByteArray {
        val count = shortArray.size
        val dest = ByteArray(count shl 1)
        for (i in 0 until count) {
            dest[i * 2] = ((shortArray[i] and 0xFFFF.toShort()).toLong() shr 0).toByte()
            dest[i * 2 + 1] = ((shortArray[i] and 0xFFFF.toShort()).toLong() shr 8).toByte()
        }
        return dest
    }
}
*/


public final class Uilts {
    static Uilts INSTANCE;

    @NonNull
    public final short[] byteArrayToShortArray(@NonNull byte[] byteArray) {
        short[] shortArray = new short[byteArray.length / 2];
        ByteBuffer.wrap(byteArray).order(ByteOrder.nativeOrder()).asShortBuffer().get(shortArray);
        return shortArray;
    }

    @NonNull
    public final byte[] shortArrayToByteArray(@NonNull short[] shortArray) {
        int count = shortArray.length;
        byte[] dest = new byte[count << 1];
        int i = 0;

        for(int cnt = count; i < cnt; ++i) {
            /*
            int j = i * 2;
            short var6 = shortArray[i];
            short var7 = (short)'\uffff';
            boolean var8 = false;
            dest[j] = (byte)((int)((long)((short)(var6 & var7)) >> 0));
            j = i * 2 + 1;
            var6 = shortArray[i];
            var7 = (short)'\uffff';
            var8 = false;
            dest[j] = (byte)((int)((long)((short)(var6 & var7)) >> 8));
             */

            dest[i * 2] = (byte)((long)((shortArray[i] & (short)0xFFFF) >> 0));
            dest[i * 2 + 1] = (byte)((long)((shortArray[i] & (short)0xFFFF)) >> 8);
        }

        return dest;
    }

    public static Uilts getInstance() {
        if (INSTANCE == null)
            INSTANCE = new Uilts();
        return INSTANCE;
    }

}